import { apiImgUrl } from "@/api";

export const useDetails = (item) => {
  const getName = () => {
    return item.title ?? item.name;
  };

  const getStars = () => {
    if (item.vote_average) {
      return item.vote_average * 10;
    }
  };

  const getYearStart = () => {
    const date = item.release_date ?? item.first_air_date;
    if (date) {
      return date.split("-")[0];
    }
  };

  const getYearEnd = () => {
    const date = item.last_air_date;
    if (date) {
      return date.split("-")[0];
    }
  };

  const getBackdrop = () => {
    if (item.backdrop_path) {
      return `${apiImgUrl}/original${item.backdrop_path}`;
    }
  };

  const getCert = () => {
    if (item.release_dates) {
      const releases = item.release_dates.results.find(
        (release) =>
          release.iso_3166_1 === import.meta.env.VITE_API_COUNTRY ||
          release.iso_3166_1 === "US"
      );
      if (!releases) return null;
      const releaseDate = releases.release_dates.find(
        (date) => date.certification !== ""
      );
      if (releaseDate) return releaseDate.certification;
    } else if (item.content_ratings) {
      const releases = item.content_ratings.results.find(
        (release) =>
          release.iso_3166_1 === import.meta.env.VITE_API_COUNTRY ||
          release.iso_3166_1 === "US"
      );
      if (!releases) return null;
      return releases.rating;
    }
  };

  const getTrailer = () => {
    if(!item.videos) return null;
    let videos = item.videos.results;
    if (!videos.length) return null;
    videos = videos.find((video) => video.type === "Trailer");
    if (!videos) return null;

    return [
      {
        name: videos.name,
        src: `https://www.youtube.com/embed/${videos.key}?rel=0&showinfo=0&autoplay=1`,
      },
    ];
  };

  const getDirectors = () => {
    if (!item.credits) return null;
    const crew = item.credits.crew;
    const directors = crew.filter((member) => member.job === "Director");
    return directors;
  };

 

  return {
    name: getName(),
    stars: getStars(),
    yearStart: getYearStart(),
    yearEnd: getYearEnd(),
    backdrop: getBackdrop(),
    cert: getCert(),
    trailer: getTrailer(),
    directors: getDirectors(),
  };
};
